package com.mg.admin.interceptor;

import com.alibaba.fastjson.JSON;
import com.mg.admin.bean.admin.Result;
import com.mg.admin.constants.ResultEnum;
import com.mg.admin.util.ConfUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * api拦截器,验证
 * 
 */
public class ApiInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String api_key = ConfUtil.getProperty("api.key");
		String g_sign = request.getHeader("sign");
		String g_Timestamp = request.getHeader("timestamp");
		String api_sigin = new String(DigestUtils.sha1Hex(api_key+g_Timestamp));
		if (api_sigin.equals(g_sign)){
			return true;
		}else {
			Result<String> result = new Result<>(ResultEnum.VERIFY_ERROR);

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.write(JSON.toJSONString(result));
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					out.close();
				}
			}
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

	public static void main(String[] args) {
		String api_sigin = new String(DigestUtils.sha1Hex("47c2d544eaba3a707278de9beefa4e301502371782455"));
		System.out.println(new Date().getTime());
		System.out.println(api_sigin);
	}

}
